package com.xiangwei.weixin;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiangwei.weixin.entity.ReceiveXmlEntity;
/**
 * 解析微信xml信息
 * */
public class ReceiveXmlProcess {
	private static final Logger logger = LoggerFactory.getLogger(ReceiveXmlProcess.class);
	public ReceiveXmlEntity getMsgEntity(String strXml){
		ReceiveXmlEntity msg = null;
		try {
			if (strXml.length()<=0 || strXml.equals("")) 
				return null;
			Document document = DocumentHelper.parseText(strXml);
			Element root = document.getRootElement();
			Iterator<?> iter = root.elementIterator(); 
			msg = new ReceiveXmlEntity(); 
			Class<?> c = Class.forName("com.xiangwei.weixin.entity.ReceiveXmlEntity");  
			msg = (ReceiveXmlEntity)c.newInstance();//创建这个实体的对象
			while(iter.hasNext()){
				Element ele = (Element) iter.next();
				Field field = c.getDeclaredField(ele.getName());
				Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());  
				method.invoke(msg, ele.getText());
			}

		} catch (Exception e) {
			logger.error("xml格式异常"+strXml);
			logger.error(e.toString());
		}
		
		return msg;
	}
}
